import { saveAs } from 'file-saver';
import main from '../main';
import { Message } from '@arco-design/web-react';

export default async function download(url: string, params: any, filename: string) {
  try {
    let res = await main.api.post(url, params, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
    });
    let data = res.data;
    let isBlob = await blobValidate([data]);
    if (isBlob) {
      let blob = new Blob([data as unknown] as BlobPart[]);
      saveAs(blob, filename);
    } else {
      // @ts-ignore
      let resText = await data.text();
      let rspObj = JSON.parse(resText);
      Message.error(rspObj.msg || '系统未知错误，请反馈给管理员');
    }
  } catch (e) {
    Message.error('下载文件出现错误，请联系管理员！');
  }
}

// 验证是否为blob格式
export async function blobValidate(data: any) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
